package com.hyfrogx.modules.zoom.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.log.LogEnum;
import com.hyfrogx.common.log.LogUtils;
import com.hyfrogx.common.utils.DateUtils;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.common.validator.ValidatorUtils;
import com.hyfrogx.modules.app.annotation.Login;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.operation.service.umeng.UmengService;
import com.hyfrogx.modules.sys.controller.AbstractController;
import com.hyfrogx.modules.sys.entity.SysUserEntity;
import com.hyfrogx.modules.zoom.entity.CallbackZoom;
import com.hyfrogx.modules.zoom.entity.HyZoomHistory;
import com.hyfrogx.modules.zoom.entity.HyZoomMeeting;
import com.hyfrogx.modules.zoom.entity.HyZoomVipUserEntity;
import com.hyfrogx.modules.zoom.form.CreateZoomForm;
import com.hyfrogx.modules.zoom.form.VipMeetForm;
import com.hyfrogx.modules.zoom.service.HyZoomHistoryService;
import com.hyfrogx.modules.zoom.service.HyZoomMeetingService;
import com.hyfrogx.modules.zoom.service.HyZoomUserService;
import com.hyfrogx.modules.zoom.service.HyZoomVipUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.Consts;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author ：Li9527
 * @date ：Created in 2019-03-27 11:18
 * @description：会议室业务模块
 * @modified By：
 * @version: 1.0
 */
@RestController
@RequestMapping("/zoom")
@Api(value = "zoom会议管理controller", tags = {"后台--会议管理"})
public class ZoomController extends AbstractController {

    @Autowired
    HyZoomMeetingService meetingService;

    @Autowired
    HyZoomVipUserService zoomVipUserService;

    @Autowired
    UserService frogUserService;

    @Autowired
    HyZoomUserService zoomUserService;

    @Autowired
    HyZoomHistoryService historyService;

    Logger zoomLog = LogUtils.Logger(LogEnum.ZOOM_LOGS);

    @Autowired
    UmengService umengService;

    /**
     * 获取Zoom回调
     *
     * @param callbackZoom
     * @param request
     * @return R
     */
    @RequestMapping(value = "callback", method = RequestMethod.POST)
    public R callback(HttpServletRequest request, CallbackZoom callbackZoom) {
        try {
            InputStream is = request.getInputStream();
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
            zoomLog.info(line);
            reader.close();
            // 获取request消息体
            zoomLog.info("the status = " + callbackZoom.getStatus() + "---------the host id = "
                    + callbackZoom.getHost_id() + "--------metting id = " + callbackZoom.getId());
            String status = callbackZoom.getStatus();

            // 如果回调为会议结束
            if (status.equals("ENDED")) {
                HyZoomMeeting meeting = meetingService.getOne(new QueryWrapper<HyZoomMeeting>().eq("zoomId", callbackZoom.getId()));
                if (meeting != null) {
                    // 发推送
                    umengService.sendEndMeet(meeting,meeting.getCurrentuid());
                    // 处理会议室
                    zoomLog.info("start update metting " + meeting.getMeetstatus());
                    meeting.setMeetstatus(0);
                    meeting.setIshavepsd(0);
                    meeting.setIscharge(0);
                    meeting.setPrice(0);
                    // 临时绑定展现id置空
                    meeting.setHymeetid(null);
                    // 密码
                    meeting.setPassword(null);
                    // 主题置空
                    meeting.setLocalname(null);
                    meeting.setTime(0);
                    Boolean result;
                    // 然后把不需要保留的数据置空
                    if (meeting.getId() != null) {
                        result = meetingService.updateById(meeting);
                        zoomLog.info("End update metting " + meeting.getMeetstatus());
                    }
                    // 找到这场会议的记录表将结束时间插入<meetHistory对象>
                    HyZoomHistory history = historyService.getOne(new QueryWrapper<HyZoomHistory>().eq("true_meet_id", callbackZoom.getId()));
                    // 查出对象不为空,才去变更
                    if (history != null) {
                        zoomLog.info("Over.Convert  meethistory Ending-----");
                        // 定义会议历史记录中的该次会议结束时间为nowTime
                        history.setEndDate(new Date());
                        // 如果是专属会议室,计算持续描述
                        if(history.getMtype() == 1){
                            Long lastTime = history.getEndDate().getTime() - history.getCreateDate().getTime();
                            history.setTime(lastTime.intValue()/1000);
                        }
                        // 持久化
                        historyService.updateById(history);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    /**
     * 通过主键id获取会议室
     *
     * @param id 会议室主键id
     * @throws MyException
     */
    @PostMapping("getMeetById")
    @ApiOperation("通过主键id获取会议室")
    public R getMeetById(@RequestParam(value = "id", required = true) Integer id) {
        try {
            HyZoomMeeting zoomMeeting = meetingService.getById(id);
            if (zoomMeeting != null) {
                // 获取主持人
                if (zoomMeeting.getCurrentuid() != null) {
                    zoomMeeting.setHostuser(frogUserService.getById(zoomMeeting.getCurrentuid()).getUsername());
                } else {
                    zoomMeeting.setHostuser("");
                }
                Map<String, Object> map = new HashMap<>();
                map.put("object", zoomMeeting);
                return R.ok(map);
            } else {
                return R.error("获取会议室失败");
            }
        } catch (MyException e) {
            return R.error(e.getMsg());
        }
    }


    /**
     * 获取会议室列表<专属>
     *
     * @param params
     * @return list
     */
    @GetMapping("/vip/zoom/list")
    @ApiOperation("获取专属会议室列表")
    public R getVipZoomlist(@RequestParam Map<String, Object> params) {
        // 获取是否有专属会议室
        params.put("orderByField", "id");
        params.put("isAsc", false);
        params.put("isvipzoom", 1);
        // 要关联查询专属名称、参会标记、所属账号【手机号】、附加账号数量、创建时间，启用时间、到期时间、
        Page page = meetingService.selectPageByConditions(new QueryExt(params));
        return R.ok().put("page", page);
    }


    /**
     * 我的会议室接口
     *
     * @param uid 用户uid
     * @throws MyException
     */
    @PostMapping("listVipZoomByUid")
    @ApiOperation("通过会议室拥有者uid获取会议室")
    public R getMeetByUid(@RequestParam(value = "uid", required = true) Integer uid) {
        try {
            Map<String, Object> params = new HashMap<>();
            // 获取是否有专属会议室
            params.put("orderByField", "endAt");
            params.put("isAsc", false);
            params.put("ouid", uid);
            // 要关联查询专属名称、参会标记、所属账号【手机号】、附加账号数量、创建时间，启用时间、到期时间、
            Page page = meetingService.selectZoomMeeting(new QueryExt<>(params));
            return R.ok().put("page", page);
        } catch (MyException e) {
            return R.error(e.getMsg());
        }
    }

    /**
     * 获取会议室列表<体验>
     *
     * @param params
     * @return list
     */
    @GetMapping("/free/zoom/list")
    @ApiOperation("获取体验会议室列表")
    public R getFreeZoomlist(@RequestParam Map<String, Object> params) {
        params.put("orderByField", "id");
        params.put("isAsc", false);
        params.put("isvipzoom", 2);
        Page page = meetingService.selectPageByConditions(new QueryExt<>(params));
        return R.ok().put("page", page);
    }

    /**
     * 获取会议室列表<普通>
     *
     * @param params
     * @return list
     */
    @GetMapping("/common/zoom/list")
    @ApiOperation("获取普通会议室列表")
    public R getCommonZoomlist(@RequestParam Map<String, Object> params) {
        params.put("orderByField", "id");
        params.put("isAsc", false);
        params.put("isvipzoom", 0);
        Page page = meetingService.selectPageByConditions(new QueryExt<>(params));
        return R.ok().put("page", page);
    }

    @PostMapping("updateShowStatus")
    @ApiOperation("显示与隐藏会议室")
    public R updateShowStatus(@RequestParam(value = "id", required = true) int id, @RequestParam(value = "showstatus", required = true) int showstatus) {
        HyZoomMeeting szMeeting = meetingService.getById(id);
        if (szMeeting.getShowstatus().equals(showstatus)) {
            return R.error("重复启用，禁用");
        }
        szMeeting.setShowstatus(showstatus);
        Boolean flag = meetingService.updateById(szMeeting);
        if (flag) {
            return R.ok();
        } else {
            return R.error("修改失败");
        }
    }

    /**
     * 会议订单管理
     *
     * @param params
     */
    @GetMapping("/listZoomHistory")
    @ApiOperation("获取会议历史")
    public R ListZoomHistory(@RequestParam Map<String, Object> params) {
        try {
            params.put("orderByField", "create_date");
            params.put("isAsc", false);
            Page page = historyService.selectPageByConditions(new QueryExt<>(params));
            if (page.getRecords() != null) {
                List<HyZoomHistory> list = page.getRecords();
                for (int i = 0; i < list.size(); i++) {
                    // 把参会者切割只计算参会者人数
                    list.get(i).setJoinId(list.get(i).getJoinId().replace("-0", "主持人"));
                    String[] numstr = list.get(i).getJoinId().split(";");
                    list.get(i).setJoinNum(numstr.length - 1);
                }
                page.setRecords(list);
                return R.ok().put("page", page);
            } else {
                return R.error("获取失败");
            }
        } catch (MyException e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 根据会议室使用记录id获取参与者信息
     *
     * @param
     */
    @GetMapping("/listZoomHistory/joinInfoById")
    @ApiOperation("根据会议室使用记录id获取参与者信息")
    public R getJoinInfoById(@RequestParam(value = "id", required = true) int id) {
        HyZoomHistory zoomHistory = historyService.getById(id);
        List<User> list = new ArrayList<>();
        if (zoomHistory != null) {
            // 把参会者切割只计算参会者人数
            String[] numstr = zoomHistory.getJoinId().split(";");
            User user;
            // 每个用户的uid
            String uid = null;
            for (int i = 0; i < numstr.length; i++) {
                uid = numstr[i];
                // 只要不是主持人本身,遍历每个用户
                if (!uid.equals("-0")) {
                    user = frogUserService.getById(uid);
                    if (user != null) {
                        list.add(user);
                    }
                }
            }
            return R.ok().put("list", list);
        } else {
            return R.error("查询错误");
        }
    }

    @PostMapping("editVipZoom")
    @ApiOperation("编辑专属会议室信息")
    public R editVipZoom(VipMeetForm vipMeetForm) {
        //表单校验
        if (vipMeetForm.getId() == null) {
            return R.error("主键id必传");
        }
        ValidatorUtils.validateEntity(vipMeetForm);
        HyZoomMeeting szMeeting = meetingService.getById(vipMeetForm.getId());
        if (szMeeting == null) {
            return R.error("对象不存在");
        }
        // 如果调整到期时间,
        if (DateUtils.stringToDate(vipMeetForm.getEndat(), DateUtils.DATE_TIME_PATTERN).getTime() < System.currentTimeMillis()) {
            return R.error("不允许设置小于当前时间的到期时间");
        }
        szMeeting.setZoomname(vipMeetForm.getZoomname());
        szMeeting.setZoomtab(vipMeetForm.getZoomtab());
        szMeeting.setEndat(DateUtils.stringToDate(vipMeetForm.getEndat(), DateUtils.DATE_TIME_PATTERN));
        szMeeting.setRemark(vipMeetForm.getRemark());
        Boolean flag = meetingService.updateById(szMeeting);
        if (flag) {
            return R.ok();
        } else {
            return R.error("修改失败");
        }
    }

    /**
     * 交互api,创建zoom会议室
     *
     * @param form
     * @throws MyException
     */
    @Login
    @PostMapping("createMeeting")
    @ApiOperation("交互api,创建会议室")
    public R createMeeting(CreateZoomForm form) throws Exception {
        try {
            Long userId = getUser().getUserId();
            zoomLog.info("创建会议室log------创建人uid为-------" + userId);
            if(userId != 1 && userId != 23){
                return  R.error("您没有权限调用该接口");
            }
            // 接口为组合接口,需要分步完成,后续可考虑form表单提交
            // 1.判断这个专属会议室名称和加入标记有没有存在,可以用selectOne查询有否对象,存在不允许创建会议室
            HyZoomMeeting nameMeeting = meetingService.getOne(new QueryWrapper<HyZoomMeeting>().eq("zoomName", form.getZoomname()));
            if (nameMeeting != null) {
                return R.error("会议室名称已存在");
            }
            HyZoomMeeting tabMeeting = meetingService.getOne(new QueryWrapper<HyZoomMeeting>().eq("zoomTab", form.getZoomtab()));
            if (tabMeeting != null) {
                return R.error("会议室唯一进入标记已存在");
            }
            // 2.判断输入手机号是否存在于我们数据库user表中
            User userEntity = frogUserService.getOne(new QueryWrapper<User>().eq("phone", form.getPhone()));
            if (userEntity == null) {
                return R.error("不存在平台的手机号");
            }
            // 3.方数不允许超过300小于10,到期时间不允许小于当前,超过5年
            if (form.getMeetingcapacity() > 300 || form.getMeetingcapacity() < 10) {
                return R.error("不允许输入的会议室规格");
            }
            if (DateUtils.stringToDate(form.getEndat(), DateUtils.DATE_TIME_PATTERN).getTime() < System.currentTimeMillis()) {
                return R.error("会议室到期时间不允许小于当前");
            }
            // 4.创建zoom账号
            String hostid = zoomUserService.creatZoomUser(userEntity.getUid(), form.getMeetingcapacity());

            // 5.创建账号成功.创建zoom会议室
            HyZoomMeeting zoomMeeting = new HyZoomMeeting();
            // 设置会议室名,会议室标记,到期时间,继承方数,用户uid,zoomApi的用户id
            zoomMeeting.setZoomname(form.getZoomname());
            zoomMeeting.setZoomtab(form.getZoomtab());
            zoomMeeting.setEndat(DateUtils.stringToDate(form.getEndat(), DateUtils.DATE_TIME_PATTERN));
            zoomMeeting.setUid(userEntity.getUid());
            zoomMeeting.setMeetingcapacity(form.getMeetingcapacity());
            zoomMeeting.setHostid(hostid);
            if (form.getRemark() != null) {
                zoomMeeting.setRemark(form.getRemark());
            }
            Integer result = meetingService.createMeetZoom(zoomMeeting);
            if (result > 0) {
                return R.ok();
            } else {
                return R.error("创建会议室成功");
            }
        } catch (MyException e) {
            return R.error(e.getMsg());
        }
    }


    @PostMapping("add/subAccount")
    @ApiOperation("新增子账号,必穿phone,zuid,zid")
    public R addSubAccount(HyZoomVipUserEntity zoomVipUserEntity) {
        User user = frogUserService.getOne(new QueryWrapper<User>().eq("phone", zoomVipUserEntity.getPhone()));
        if (user == null) {
            return R.error("该账号不存在");
        }
        List<HyZoomVipUserEntity> result = zoomVipUserService.list(new QueryWrapper<HyZoomVipUserEntity>().eq("ouid", user.getUid()).eq("zid", zoomVipUserEntity.getZid()));
        if (result.size() > 0) {
            return R.error("该会议室已存在此子账号");
        }

        SysUserEntity sysUserEntity = getUser();
        zoomVipUserEntity.setOuid(user.getUid().intValue());
        zoomVipUserEntity.setOperatorUid(sysUserEntity.getUserId().intValue());
        if (zoomVipUserService.add(zoomVipUserEntity) > 0) {
            return R.ok("创建成功");
        }
        return R.error("创建失败");
    }

    @GetMapping("update/subAccount")
    @ApiOperation("编辑子账号,必穿id,必穿statu,1启用0禁用")
    public R updateSubAccount(Integer id, Integer statu) {
        HyZoomVipUserEntity zoomVipUserEntity = new HyZoomVipUserEntity();
        zoomVipUserEntity.setId(id);
        zoomVipUserEntity.setStatu(statu);
        zoomVipUserEntity.setOperatorUid(getUser().getUserId().intValue());
        zoomVipUserEntity.setUpdateat(new Date());
        if (zoomVipUserService.updateById(zoomVipUserEntity)) {
            return R.ok();
        }
        return R.error();
    }

    @GetMapping("list/subAccount")
    @ApiOperation("子账号列表,zid")
    public R listSubAccount(@RequestParam(value = "zid", required = true) Integer zid) {
        List<HyZoomVipUserEntity> result = zoomVipUserService.list(new QueryWrapper<HyZoomVipUserEntity>().eq("zid", zid));
        if (result.size() > 0) {
            String phone;
            for (HyZoomVipUserEntity zoomUser : result) {
                phone = frogUserService.getOne(new QueryWrapper<User>().eq("uid", zoomUser.getOuid())).getPhone();
                zoomUser.setOphone(phone);
            }
            return R.ok().put("result", result);
        }
        Integer[] n = new Integer[0];
        return R.ok().put("result", n);
    }


}
